package com.google.protobuf
{
	import avmplus.getQualifiedClassName;
	
	import flash.utils.Dictionary;

	public class Service
	{
		static protected var _services 	: Vector.< Service > = new Vector.<Service>;
		static protected var _services_d: Dictionary = new Dictionary;
		
		static public function getServiceByName(name:String) : Service { return _services_d[name] ;}
		static public function getServiceByIndex(idx:int) : Service { return _services[idx] ;};
		
		protected var _methods   :Vector.< MethodDescriptor > = new Vector.< MethodDescriptor >;
		protected var _methods_d :Dictionary = new Dictionary;
		
		private var _descriptor:ServiceDescriptor ;
		
		public function Service(name:String , index:int)
		{
			_descriptor = new ServiceDescriptor(name , index);
			
			_services.push(this);
			_services_d[name] = this;
		}
		
		public function get descriptor() : ServiceDescriptor
		{
			return _descriptor;
		}
		
		public function callMethod( method:MethodDescriptor ,controller:RpcController,request:MessageLite,response:MessageLite,done:Closure):void
		{
			if(method.index >= _methods.length) 
				throw new Error("method cann`t find");
			
			var method_name :String = _methods[method.index].name;
			
			this[method_name](controller , request , response , done);
		}
		

		
		protected function _register_method(name:String,idx:int,input:String,output:String):void
		{
			var m :MethodDescriptor = new MethodDescriptor(name,_descriptor,idx,input,output);
			_methods.push(m);
			_methods_d[name] = m;
		}
		
		public function getMethodByIndex(idx:int):MethodDescriptor
		{
			if(idx > _methods.length) return null;
			return _methods[idx];
		}
	}
}